/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package comum;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author root
 */
public class Message {

    //tripaseca!~blaster@177.35.240.169 PRIVMSG #TADS :away
    //
    // parametro = away
    // source = nick/canal/server <- tripaseca
    // comand = PRIVMSG
    // terget = TADS <- canal poderia ser para um nick ou sever
    private String parameter;
    private MsgSource source;
    private String command;
    private MsgSource target;
    private boolean serverToClient;

    public Message() {
    }

    
    public Message(String l) {
        if (l != null) {
            if (l.startsWith(":")) {
                serverToClient = true;
            } else {
                serverToClient = false;
            }
            Pattern pattern = Pattern.compile("^(?:[:@]([^\\s]+) )?([^\\s]+)(?: ((?:[^:\\s][^\\s]* ?)*))?(?: ?:(.*))?$");
            // Pattern pattern = Pattern.compile("'/^(.*)!(.*)@(.*) (.*) (.*) :(.*)$/'");

            Matcher matcher = pattern.matcher(l.subSequence(0, l.length()));
            if (matcher.matches()) {
                this.source = new MsgSource(matcher.group(1));
                if (matcher.group(2) != null) {
                    this.command = matcher.group(2).trim().toUpperCase();
                } else {
                    this.command = "";
                }
                this.target = new MsgSource(matcher.group(3));

                if (matcher.group(4) != null) {
                    this.parameter = matcher.group(4).trim();
                } else {
                    this.parameter = "";
                }
            }
        }
    }

    public Message(String source, String cmd, String target, String parameter, boolean serverToClient) {
        this.source = new MsgSource(source);
        this.command = cmd;
        this.target = new MsgSource(target);
        this.parameter = parameter;
    }

    public String getCommand() {
        return command;
    }

    public String getParameter() {
        return parameter;
    }

    public String getSourceName() {
        return source.getStringName();
    }

    public String getTargetName() {
        return target.getStringName();
    }

    public MsgSource getSource() {
        return source;
    }

    public MsgSource getTarget() {
        return target;
    }

    @Override
    public String toString() { //gambi +- ok
        String ret = "";
        if (serverToClient) {
            ret = ":" + source.getStringName() + " ";
        }

        ret += command + " ";

        if (target.getStringName() != null && !target.getStringName().equals("")) {
            ret += target.getStringName() + " ";
        }
        if (parameter != null) {
            ret += ":" + parameter + " ";
        }
        return ret.trim();
    }
}
